<?php

declare(strict_types=1);

namespace app\middleware;

use think\facade\View;

class admin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        if ($request->layer() === 'admin') {
            $User = session('user');
            $suffix = config('route.controller_suffix') ? "" : "Controller"; //控制器后缀
            if (!isset($User) && $request->controller() . $suffix != "LoginController") {
                return error("请先登录", "admin.login.log");
            } else {
                if ($request->controller() . $suffix != 'LoginController') {
                    //鉴权
                    $UserAuth = session('auth');
                    if ($UserAuth["rid"] > 0) {
                        $AuthArr = json_decode($UserAuth["auth"], true); //已拥有的权限
                        $class = new \ReflectionMethod('\\' . $request->controller() . $suffix, $request->action());
                        $attributes = $class->getAttributes(\app\common\Attribute::class);
                        $AuthThen = $attributes[0]->newInstance()->fun(); //当前权限
                        if ($AuthThen["isAuth"]) { //需要鉴权

                            $controller = $request->controller();

                            if (!in_array("{$controller}@{$request->action}", $AuthArr)) {
                                return error("您没有该权限", "#");
                            }
                        }
                    }
                }
                View::assign("user", $User);
            }
        }
        return $next($request);
    }
}
